import Vue from 'vue'
import Axios from 'axios'
import Router from "vue-router"
Vue.use(Router)

export const axios_token = Axios.create({
    timeout: 1000 * 30,                     // 超时时间
    withCredentials: true,                  // 跨域携带cookie
    crossDomain: true,
    // retry: 4,                               // 设置重新请求
    // retryDelay: 1000,
    responseType: "json",
    // serverUrl: serverUrl
})
// 配置拦截器，取消所有请求
window.axiosCancel = []
//请求拦截
axios_token.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8'
    const user = localStorage.getItem('userAllInfos');
    if (user) {
        config.headers.Authorization = JSON.parse(localStorage.getItem('userAllInfos')).token
    }
    return config;
}, err => {
    return Promise.reject(err)
})
//响应拦截
axios_token.interceptors.response.use(response => {
    console.log("response----", response)
    const result = response.data
    const responseType = response.config.responseType
    if (responseType === 'json') {
        if (result && response.status === 200) {
            if (result.code === 401) {
                Vue.prototype.$notify.error({
                    title: "请先登录",
                    message: "认证失败"
                });
                new Router (
                    {
                        path: "/",
                        redirect: "/login"
                    })
            }
            return Promise.resolve(result)
        }
        return Promise.reject(result);
    }
}, error => {
    console.log("error----", error);
    if (error.response && error.response.status === 401) {
        localStorage.removeItem('userAllInfos'); // 移除无效的JWT
    }

    if (error.code === "ECONNABORTED" && error.message.indexOf('timeout') !== -1) {
        Vue.prototype.$notify.error({
            title: "消息",
            message: "请求超时"
        });
    }
// 请求错误的处理
    const msg = {
        "400": "请求错误",
        "401": "未授权，请登录",
        "403": "拒绝访问",
        "404": `请求地址出错`,
        "408": "请求超时",
        "500": "服务器内部错误",
        "501": "服务未实现",
        "502": "网关错误",
        "503": "服务不可用",
        "504": "网关超时",
        "505": "HTTP版本不受支持"
    };
    if (error.response) {
        Vue.prototype.$notify.error({
            title: "消息",
            message: msg[error.response.status]
        });
    }
    return Promise.reject(error);
})
Vue.prototype.$axios_token = axios_token;
